package com.spa.application.service.member;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.spa.application.command.member.MemberUserInfoEditCommand;
import com.spa.application.dto.member.MemberUserInfoDTO;
import com.spa.domain.entity.UserAddress;
import com.spa.domain.entity.UserInfo;
import com.spa.domain.entity.UserTicket;
import com.spa.domain.service.AddressService;
import com.spa.domain.service.CouponService;
import com.spa.domain.service.UserInfoService;
import com.spa.domain.service.UserTicketService;
import com.spa.infrastructure.mapper.UserInfoMapperStruct;
import com.spa.infrastructure.util.SessionUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
@Data
public class MemberUserApplicationService {

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private AddressService addressService;

    @Resource
    private UserTicketService userTicketService;

    @Autowired
    private CouponService couponService;

    /**
     * 获取用户详情
     *
     * @author: lig
     * @date: 2023/12/6
     */
    public MemberUserInfoDTO userInfo() {
        UserInfo userInfo = userInfoService.userInfoById(SessionUtil.getUser().getExtUserId());
        MemberUserInfoDTO memberUserInfoDTO = UserInfoMapperStruct.INSTANCE.entity2Dto(userInfo);
        List<UserAddress> addressList = addressService.listByUserId(SessionUtil.getUser().getExtUserId());
        if(CollUtil.isNotEmpty(addressList)){
            memberUserInfoDTO.setAddressCount(Convert.toInt(addressList.size(), 0));
        }else {
            memberUserInfoDTO.setAddressCount(0);
        }
        List<UserTicket> ticketList = userTicketService.listByUserId(SessionUtil.getUser().getExtUserId());
        if(CollUtil.isNotEmpty(ticketList)){
            memberUserInfoDTO.setCouponCount(Convert.toInt(ticketList.size(), 0));
        }else {
            memberUserInfoDTO.setCouponCount(0);
        }

        //收藏数
        memberUserInfoDTO.setCollectionCount(userInfoService.userCollectionNum(SessionUtil.getUser().getExtUserId()));


        memberUserInfoDTO.setName(Convert.toStr(userInfo.getName(), ""));
        long number = couponService.countByUser(userInfo.getId());

        memberUserInfoDTO.setCouponNumber(Convert.toLong(number, 0L));
        return memberUserInfoDTO;

    }

    /**
     * 修改用户信息
     *
     * @author: lig
     * @date: 2023/12/6
     */
    public void editUserInfo(MemberUserInfoEditCommand command) {
        log.info("{}",command.getAvatar());
        userInfoService.editUserInfo(command);
    }

}
